package org.truenewx.tnxjee.core.ref;

import java.util.*;

/**
 * 引用计数器
 *
 * @author jianglei
 */
public class ReferenceCounter {

    private boolean exists;
    private final Map<Class<?>, Long> types = new HashMap<>();
    private final List<Object> objects = new ArrayList<>();

    public void setExists(boolean exists) {
        this.exists = exists;
    }

    public boolean exists() {
        return this.exists || !this.types.isEmpty() || !this.objects.isEmpty();
    }

    public long countType(Class<?> referenceType) {
        Long count = this.types.get(referenceType);
        return count == null ? 0 : count;
    }

    public synchronized long addType(Class<?> referenceType, long count) {
        long c = countType(referenceType);
        c += count;
        this.types.put(referenceType, c);
        return c;
    }

    public int addObject(Object referencer) {
        this.objects.add(referencer);
        return this.objects.size();
    }

    public synchronized long getTotal() {
        long total = 0;
        for (Long count : this.types.values()) {
            total += count;
        }
        total += this.objects.size();
        return total;
    }

    public Collection<Class<?>> getTypes() {
        return Collections.unmodifiableSet(this.types.keySet());
    }

    public Collection<Object> getObjects() {
        return Collections.unmodifiableList(this.objects);
    }

}
